<?php

namespace App\Http\Controllers\Topic\Topic;

use App\Models\Topic\Topic;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Topic\Topic\TopicRequest;
use TopicShow;
use TopicSave;
use CategoriesShow;
use App\Handlers\ImageUploadHandler;
use App\Models\Topic\Link;
class TopicsController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }

    public function index(Request $request, Topic $topic, User $user, Link $link)
	{
        $topics =TopicShow::index($request,$topic);
        $active_users = $user->getActiveUsers();
        $links = $link->getAllCached();
        return view('topics.topic.index', compact('topics','active_users','links'));
	}

    public function show(Request $request,Topic $topic)
    {
        if ( ! empty($topic->slug) && $topic->slug != $request->slug) {
            return redirect($topic->link(), 301);
        }
        return view('topics.topic.show', compact('topic'));
    }

	public function create(Topic $topic)
	{
        $categories=CategoriesShow::index();
		return view('topics.topic.create_and_edit', compact('topic','categories'));
	}

	public function store(TopicRequest $request, Topic $topic)
	{
        $topic_id = TopicSave::store($request,$topic);
		return redirect()->to($topic->link())->with('success', '成功创建话题！');
	}

	public function edit(Topic $topic)
	{
        $this->authorize('update', $topic);
        $categories=CategoriesShow::index();
        return view('topics.topic.create_and_edit', compact('topic','categories'));
	}

	public function update(TopicRequest $request, Topic $topic)
	{
		$this->authorize('update', $topic);
		$topic->update($request->all());
		return redirect()->to($topic->link())->with('success', '修改成功');
	}

	public function destroy(Topic $topic)
	{
		$this->authorize('destroy', $topic);
        TopicSave::destroy($topic);
		return redirect()->route('topics.index')->with('message', '删除成功');
	}
    public function uploadImage(Request $request, ImageUploadHandler $uploader)
    {
        return TopicSave::uploadImage($request,$uploader);
    }
}
